package com.common.view;

import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.tushen.datacenter.ts.R;

public class PopwindowUtil {
	
	
	protected static final String TAG = "PopwindowUtil";

    public static PopupWindow showPopwindow(Context c,final View rootView,final OnClickListener okClickListener){

        try{
            if(c == null || rootView == null){
                Log.d(TAG,"showPopwindow parameter error...");
                return null;
            }
            LinearLayout contentView = (LinearLayout)LayoutInflater.from(c).inflate(R.layout.popwindow,null);

            ViewAdjust.adjustLayoutParams(c, contentView.findViewById(R.id.root_view));

            final PopupWindow p = new PopupWindow(contentView,
                    ViewAdjust.getWidthPxAdjust(c, 800),
                    ViewAdjust.getHeightPxAdjust(c, 600));
            p.setFocusable(true);

            final Button okButton = (Button)contentView.findViewById(R.id.ok_btn);
            final EditText editText = (EditText)contentView.findViewById(R.id.txt);


            okButton.setFocusable(true);

            okButton.setOnKeyListener(new OnKeyListener() {

                @Override
                public boolean onKey(View arg0, int keycode, KeyEvent event) {
                    if(event.getAction() == KeyEvent.ACTION_UP){
                        return false;
                    }

                    if(keycode == KeyEvent.KEYCODE_BACK ){
                        p.dismiss();
                    }else if(keycode == KeyEvent.KEYCODE_DPAD_CENTER || keycode == KeyEvent.KEYCODE_ENTER){
                        if(okClickListener != null){
                            okClickListener.onClick(editText);
                        }
                        p.dismiss();
                    }else if(keycode == KeyEvent.KEYCODE_DPAD_LEFT || keycode == KeyEvent.KEYCODE_DPAD_UP ){
                        editText.requestFocus();
                    }
                    return true;
                }
            });

            okButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(okClickListener != null){
                        okClickListener.onClick(editText);
                    }
                    p.dismiss();
                }
            });
            editText.requestFocus();
            return p;
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"showPopwindow catch Exception e = "+e.getClass().getSimpleName());
        }
        return null;
	}



}
